package meijuli.com.join51.business.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.jhx.common.http.ApiManager;
import com.jhx.common.http.HttpRequest;
import com.jhx.common.http.HttpResponse;
import com.jhx.common.http.ResponseCallback;
import com.jhx.common.model.User;
import com.jhx.common.utils.ImageLoader;
import com.jhx.common.utils.ToastUtil;
import com.jhx.common.utils.UserManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import meijuli.com.join51.business.R;
import meijuli.com.join51.business.activity.ChangeNameActivity;
import meijuli.com.join51.business.activity.UserInfoActivity;
import meijuli.com.join51.business.aliyun.ImageUtils;
import com.jhx.common.model.EventBean;
import meijuli.com.join51.business.model.UserData;
import meijuli.com.join51.business.service.ApiService;
import meijuli.com.join51.business.utils.SoftInputUtil;
import retrofit2.Call;

/**
 * 商家信息页面
 *
 * @author wenqin 2017-04-14 17:31
 */
public class UserInfoFragment extends PhotoFragment implements ImageUtils.SelectImageListener {
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private Call<HttpResponse<UserData>> mCall;
    private Call<HttpResponse<String>> call;
    private TextView mDiscountTxt;
    private TextView mNameText;
    private TextView mTitleText;
    private TextView mPhoneText;
    private ImageView mHeadImg;
    private User mUser;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_user_message, container, false);
        if(!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        mSwipeRefreshLayout = view.findViewById(R.id.swipe_refresh_layout);
        mDiscountTxt = view.findViewById(R.id.txt_discount);
        mPhoneText = view.findViewById(R.id.txt_phone);
        mNameText = view.findViewById(R.id.txt_name);
        mTitleText = view.findViewById(R.id.txt_title);
        mHeadImg = view.findViewById(R.id.img_head);
        return view;
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (UserManager.get().checkUserNull(getActivity())) {
            return;
        }
        mUser = UserManager.get().getUser();
        if(!TextUtils.isEmpty(UserManager.get().getDiscount())){
            mDiscountTxt.setText(UserManager.get().getDiscount() + "%");
        } else {
            mTitleText.setVisibility(View.GONE);
            mDiscountTxt.setVisibility(View.GONE);
        }
        if(!TextUtils.isEmpty(mUser.getBusinessName())) {
            mNameText.setText(mUser.getBusinessName());
        }
        if(!TextUtils.isEmpty(mUser.getPhone())) {
            mPhoneText.setText(mUser.getPhone());
        }
        ImageLoader.Companion.get().loadCircleImageByUrl(getActivity(), mUser.getHeadImage(), mHeadImg);
        initListener();
    }

    private void initListener() {
        mHeadImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showListDialog();
            }
        });
        mNameText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), ChangeNameActivity.class);
                startActivity(intent);
            }
        });
    }

    private void requestUserMsg() {
        if (!mSwipeRefreshLayout.isRefreshing()) {
            mSwipeRefreshLayout.setRefreshing(true);
        }
        mCall = ApiManager.get().getApiService(ApiService.class).getUserInfo();
        HttpRequest.getRequest().autoRecycle(this).start(mCall, new ResponseCallback<UserData>() {

            @Override
            public void onSuccess(String url, UserData data) {
                mUser = data.getUser();
                if (mUser != null) {
                    UserManager.get().setUser(mUser);
                } else {
                    ToastUtil.getInstance().showToast("获取数据失败");
                }
                mSwipeRefreshLayout.setRefreshing(false);
                EventBus.getDefault().post(new EventBean<>(EventBean.STATUS_HOME_MSG));
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                super.onError(url, errorCode, errorMsg);
                mSwipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            ((UserInfoActivity) mActivity).setToolBarTitle("商家信息");
            SoftInputUtil.get().hideSoftKeyboard(mActivity);
        }
    }


    @Override
    protected void onUpLoadSuccess(String cloudKey, String sourceFilePath) {
        uploadHeadIcon(cloudKey);
    }

    private void uploadHeadIcon(final String cloudKey) {
        call = ApiManager.get().getApiService(ApiService.class).uploadHeadIcon(cloudKey);
        HttpRequest.getRequest().autoRecycle(this).start(call, new ResponseCallback<String>() {

            @Override
            public void onSuccess(String url, String data) {
                dismissDialog();
                if (TextUtils.isEmpty(data)) {
                    ToastUtil.getInstance().showToast("无法正确获取数据，上传图片失败，请退出重试");
                    return;
                }
                ImageLoader.Companion.get().loadCircleImageByUrl(getActivity(), data, mHeadImg);
                mUser.setHeadImage(data);
                UserManager.get().setUser(mUser);
                EventBus.getDefault().post(new EventBean<>(EventBean.STATUS_HOME_MSG));
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                super.onError(url, errorCode, errorMsg);
                dismissDialog();
            }
        });
    }

    @Subscribe
    public void onEvent(EventBean bean) {
        switch (bean.getStatus()) {
            case EventBean.STATUS_MSG:
                requestUserMsg();
                break;
            default:

                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if(EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
